package com.bms.cfcmms.controller;

import com.bms.cfcmms.util.SpringUtils;
import com.bms.cfcmms.util.annotation.FieldDefine;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

/**
 * Created by carl on 2017/3/19.
 */
@Data
public class BaseController {

    private static final Logger log = LoggerFactory.getLogger(BaseController.class);

    private String operDescInfo;

    @ExceptionHandler
    public String exp(HttpServletRequest request, Exception ex) {
        String resultViewName = "errors/error";
        // 记录日志
        log.error(ex.getMessage(), ex);
        request.setAttribute("ex", ex);

        return resultViewName;
    }

    public void setOperDescInfo(Object object) {

        Field[] fields = object.getClass().getDeclaredFields();
        StringBuilder stringBuilder = new StringBuilder("");

        for (Field field : fields) {
            FieldDefine fieldDefine = field.getAnnotation(FieldDefine.class);
            Object value = findValueOfField(object, field, fieldDefine);
            if (value == null) {
                continue;
            }
            String fieldKey = object.getClass().getSimpleName() + "." + field.getName();
            String fieldName = SpringUtils.getMessage(fieldKey);
            stringBuilder.append(fieldName).append("=").append(String.valueOf(value)).append(";");
        }
        this.operDescInfo = stringBuilder.toString();
    }

    private Object findValueOfField(Object object, Field field, FieldDefine fieldDefine) {
        Object value = null;
        if (fieldDefine == null) {
            return null;
        }
        field.setAccessible(true);
        try {
            value = field.get(object);
            if (value == null) {
                return null;
            }
        } catch (IllegalAccessException e) {
            log.warn("", e);
        }
        return value;
    }
}
